package com.eh.mitakebus;

import com.eh.eventbus.EventBusException;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangxiaowei on 17/4/26.
 */

class SubscriberMethodFinder {
    private static final Map<String, List<SubscriberMethod>> methodCache = new HashMap<>();

    public List<SubscriberMethod> getMitakeMethod(Class clazz) {

        List<SubscriberMethod> methodList;
        synchronized (methodCache) {
            methodList = methodCache.get(clazz);
        }
        if (methodList != null) {
            return methodList;
        }
        methodList=new ArrayList<>();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (methodName.startsWith("onMitake")) {
                Class[] methPt = method.getParameterTypes();
                if (methPt != null && methPt.length == 1) {
                    SubscriberMethod subscriberMethod = new SubscriberMethod(method, methPt[0]);
                    methodList.add(subscriberMethod);
                }
            }
        }
        if (methodList.isEmpty()) {
            throw new EventBusException("Subscriber " + clazz + " has no public methods called "
                    + "onMitake");
        } else {
            synchronized (methodCache) {
                methodCache.put(clazz.getName(), methodList);
            }
            return methodList;
        }
    }
}
